package apiWeb

import (
	user "ZHONGYIHANGYAN/business/user"
	"fmt"

	"ZHONGYIHANGYAN/web"

	requset "ZHONGYIHANGYAN/bean/request"

	"github.com/gin-gonic/gin"
)

func (api *Api) UserRouters(g *gin.RouterGroup) {
	routerG := g.Group("/user")
	{
		// 获取用户列表
		routerG.POST("/getUserList", web.NewWebRouter(api.getUserList).Func)
		// 添加或修改用户
		routerG.POST("/addOrUpdateUser", web.NewWebRouter(api.addOrUpdateUser).Func)
		// 删除用户
		routerG.POST("/deleteUser", web.NewWebRouter(api.deleteUser).Func)
	}
}

func (api *Api) InitUserRouter() error {
	api.userManage = user.Manage()
	api.web.RegRouters(api.UserRouters)
	return nil
}

// 获取用户列表
func (api *Api) getUserList(c *gin.Context, replayData *interface{}) error {
	query := requset.GetUserListQuery{}
	if err := api.web.GetPayload(c, &query); err != nil {
		return err
	}
	infoList, err := api.userManage.GetUserList(&query)
	if err != nil {
		return err
	}
	*replayData = infoList
	return nil
}

// 添加或修改用户
func (api *Api) addOrUpdateUser(c *gin.Context, replayData *interface{}) error {
	info := requset.AddOrUpdateUserQuery{}
	if err := api.web.GetPayload(c, &info); err != nil {
		return err
	}
	if err := api.userManage.AddOrUpdateUser(&info); err != nil {
		return err
	}
	return nil
}

// 删除用户
func (api *Api) deleteUser(c *gin.Context, replayData *interface{}) error {
	query := requset.DeleteUserQuery{}
	if err := api.web.GetPayload(c, &query); err != nil {
		return err
	}
	if len(query.UserIds) == 0 {
		return fmt.Errorf("请传入需要删除的用户id")
	}
	if err := api.userManage.DeleteUser(query.UserIds); err != nil {
		return err
	}
	return nil
}
